package com.fzy.core;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ServletRequestAware;

import com.fzy.core.entity.EntityId;
import com.opensymphony.xwork2.ActionSupport;

public class BaseAction extends ActionSupport implements ServletRequestAware {
	/**
	 * 
	 */
	private static final long serialVersionUID = 2925430793127104593L;
	private static final Logger log = Logger.getLogger(BaseAction.class);
	protected HttpServletRequest request;

	protected EntityId validateId(String idString, Class clazz) {
		Object entityObj = null;
		if (!StringUtils.isBlank(idString)) {
			Long id = null;
			try {
				long i = Long.parseLong(idString.trim());
				id = new Long(i);
			} catch (NumberFormatException e) {
				addActionError(getText("error.idError",
						new String[] { idString }));
			}
			if (id != null) {
				entityObj = U.getBaseService().get(clazz, id);
				if (entityObj == null) {
					addActionError(getText("error.entityMissing",
							new String[] { idString }));
				}
			}
		}
		if (entityObj == null) {
			try {
				entityObj = clazz.newInstance();
			} catch (InstantiationException e) {
				log.error(e.getMessage(), e);
			} catch (IllegalAccessException e) {
				log.error(e.getMessage(), e);
			}
		}

		return (EntityId) entityObj;
	}

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

}
